package de.uni.leipzig.meddins.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import de.uni.leipzig.meddins.R;
import de.uni.leipzig.meddins.app.AppSettings;
import de.uni.leipzig.meddins.server.ServerService;

public class DroidSocketServerActivity extends Activity {
	
	private Intent service;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		service = new Intent(DroidSocketServerActivity.this, ServerService.class);
		setButtonHandlers();
		boolean isRunning = AppSettings.isServiceStarted(DroidSocketServerActivity.this);

		setButtonText(isRunning);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.contextmenu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		boolean result = true;
		
	    switch (item.getItemId()) {
	        case R.id.menuPreference:{
	        	startActivity(new Intent(this,DSSPreferenceActivity.class));
	            break;
	        }
	        default:{
	            result = super.onOptionsItemSelected(item);
	        }
	    }
	    
	    return result;
	}
	 
	 

	private void setButtonHandlers() {
		((Button) findViewById(R.id.button_start_stop))
				.setOnClickListener(btnClick);

	}

	private void setButtonText(boolean isServiceRunning) {
		((Button) findViewById(R.id.button_start_stop))
				.setText(getString(isServiceRunning ? R.string.button_stop
						: R.string.button_start));
	}
	
	private View.OnClickListener btnClick = new View.OnClickListener() {
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.button_start_stop: {

				if (AppSettings.isServiceStarted(DroidSocketServerActivity.this)) {
					stopService(service);
					AppSettings.setServiceStarted(DroidSocketServerActivity.this, false);
					setButtonText(false);
				} else {
					startService(service);
					AppSettings.setServiceStarted(DroidSocketServerActivity.this, true);
					setButtonText(true);
				}

				break;
			}
			}
		}
	};
}